<?php

namespace App\Listeners\OpenShop\IntendedSiteSelection;

use App\Enums\OpenShop\Merchant\IntendedSiteLocationEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Events\OpenShop\IntendedSiteSelection\InsertEvent;
use App\Library\FeiShu\SendFs;
use App\Models\Common\ConfigModel;
use App\Models\Common\FsMessageTemplateModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\SiteLocation\IntendedSiteSelectionModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\Common\CommonService;
use App\Service\OpenShop\Feishu\BaseService;
use App\Support\FeishuMsgSupport;
use Carbon\Carbon;
use Guanguans\Notify\Factory;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\View\Compilers\BladeCompiler;
use Kuafu\GeneralFs\BuildFs;

class InsertListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param InsertEvent $insertEvent
     * @return void
     * @throws GuzzleException
     * @throws \Exception
     */
    public function handle(InsertEvent $insertEvent)
    {
        try {
            self::handleBusiness($insertEvent->intendedSiteSelectionId, $insertEvent->status, $insertEvent->record);
        } catch (\Exception $exception) {
            logException("意向选址添加消息推送失败", $exception, ["id" => $insertEvent->intendedSiteSelectionId], true, true);
        }
    }

    /**
     * @param int $intendedSiteSelectionId
     * @throws GuzzleException
     * @throws \Exception
     */
    public static function handleBusiness(int $intendedSiteSelectionId, $status, $record)
    {
        $intendedSiteSelectionModel = IntendedSiteSelectionModel::query()
                                                                ->with([
                                                                    "shopRel" => function ($query) {
                                                                        $query->with([
                                                                            "signOrderRel" => function ($query) {
                                                                                $query->with([
                                                                                    "developmentConsultantRel",
                                                                                    "progressRel",
                                                                                    "startBusinessRel",
                                                                                    "contractRel"
                                                                                ]);
                                                                            }
                                                                        ]);
                                                                    }
                                                                ])
                                                                ->where("id", $intendedSiteSelectionId)
                                                                ->first();

        $signOrder                = attributeGet($intendedSiteSelectionModel, "shopRel.signOrderRel", null);
        $nowStepStatus            = attributeGet($signOrder, "progressRel.nowStepStatus", null);
        $startBusiness            = attributeGet($signOrder, "startBusinessRel", null);
        $contractRel              = attributeGet($signOrder, "contractRel", null);
        $developmentConsultantRel = attributeGet($signOrder, "developmentConsultantRel", null);

        // todo 获取开发顾问数据
        $fsUserId  = "";
        $developmentUserId = 0;
        if ($developmentConsultantRel) {
            $fsUser            = KmsUser::query()->where("rmsUserId", $developmentConsultantRel->managerUid)->first();
            $developmentUserId = $developmentConsultantRel->managerUid;
            $fsUserId          = attributeGet($fsUser, "userId", "");
        }

        // 自动添加跟进人ID
        if ($intendedSiteSelectionModel->followUpUserId == 0) {
            $intendedSiteSelectionModel->followUpUserId = $developmentUserId;
            $intendedSiteSelectionModel->status         = IntendedSiteLocationEnum::INTENDED_SITE_LOCATION_WAIT_FOLLOW_UP;
            $intendedSiteSelectionModel->save();
        }

        //todo 判断门店是否开业
        $hasOpened = false;
        if ($nowStepStatus == MissionTemplateEnum::STEP_STATUS_999) {
            $hasOpened = true;
        }

        //todo 获取模板参数数据
        $rmsUserResponse = RmsUserRemote::getRmsUserByIds([$intendedSiteSelectionModel->createdByUid]);
        if (empty($rmsUserResponse)) {
            throw new \Exception("获取rms用户信息失败");
        }
        $rmsUserInfo = $rmsUserResponse[0];

        $shopState = $followUp = "";

        if ($hasOpened) {
            $startBusinessTime = attributeGet($startBusiness, "startBusinessTime", 0);
            if ($startBusinessTime > 0) {
                $timeVal         = Carbon::createFromTimestamp($startBusinessTime)->format("Y-m-d H:i");
                $timeDurationVal = vsprintf("%s 天", [(int)((time() - $startBusinessTime) / 86400)]);
                $shopState       = '已开业' . $timeDurationVal . '(开业时间' . $timeVal . ')';
            }
            $templateHeaderColor = "blue";
        } else {
            $signTime         = attributeGet($contractRel, "signTime", 0);
            if ($signTime > 0) {
                $timeVal         = Carbon::createFromTimestamp($signTime)->format("Y-m-d H:i");
                $timeDurationVal = vsprintf("%s 天", [(int)((time() - $signTime) / 86400)]);
                $shopState       = '已签约' . $timeDurationVal . '(签约时间' . $timeVal . ')';
            }
            $templateHeaderColor = "green";
        }

        // todo 获取消息模板信息
        $templateModel = FsMessageTemplateModel::query()
                                               ->where("templateName", "INTENDED_SITE_SELECTION_INSERT")
                                               ->first();

        // todo 消息推送

        $buttonText = '立即跟进';

        $nowTime = Carbon::now()->toDateTimeString();

        if (strlen($record)) {
            $followUpFsUserId = KmsUser::query()->where('rmsUserId', $intendedSiteSelectionModel->followUpUserId)->value('userId');
            $followUpStatus   = "**跟进状态：**" . (IntendedSiteLocationEnum::INTENDED_SITE_LOCATION_MAPPING[$status] ?? '');
            $followUpUser     = '**最新跟进人：** <at id=' . $followUpFsUserId . '></at>';
            $followUpContent  = "**最新跟进记录：** " . '\n' . "{$record}";
            $followUpTime     = "**最新跟进时间：** {$nowTime}";
            $followUp         = $followUpStatus . '\n' . $followUpUser . '\n' . $followUpTime . '\n' . $followUpContent;
            $buttonText       = '查看详情';
        }

        $cardContent = json_decode(BladeCompiler::render(
            $templateModel->templateContent, [
            "username"            => CommonService::getUserInfoHide(attributeGet($rmsUserInfo, "username", ""), 'name', true),
            "mobile"              => CommonService::getUserInfoHide(attributeGet($rmsUserInfo, "mobile", ""), 'mobile', true),
            "shopState"           => $shopState,
            "addressPrefix"       => $intendedSiteSelectionModel->addressPrefix,
            "address"             => $intendedSiteSelectionModel->poiAddress,
            "submitTime"          => $intendedSiteSelectionModel->createdAt->format("Y-m-d H:i"),
            "templateHeaderColor" => $templateHeaderColor,
            "shopCode"            => attributeGet($signOrder, "shopCode", ""),
            "followUp"            => $followUp,
            "buttonText"          => $buttonText,
            "buttonUrl"           => BaseService::getIntendedSiteLocationUrl($intendedSiteSelectionId, $intendedSiteSelectionModel->latitude, $intendedSiteSelectionModel->longitude),
        ]), true);

        BuildFs::newRobot(SendFs::ROBOT_INTENDED_SITE_SELECTION_INSERT, BuildFs::MSG_TYPE_CARD)->setCardContent($cardContent)->send();

        // 给开发发消息
        if ($developmentUserId && !strlen($record)) {
            FeishuMsgSupport::getInstance('有新的意向址提交，请查看',
                array_merge([$developmentUserId]))
                ->setContent(
                    ["name" => "意向区域", "value" => $intendedSiteSelectionModel->addressPrefix],
                    ["name" => "门店编号", "value" => attributeGet($signOrder, "shopCode", "")],
                    ["name" => "门店状态", "value" => $shopState],
                    ["name" => '客户姓名', "value" => attributeGet($rmsUserInfo, "username", "")],
                    ["name" => '客户电话', "value" => attributeGet($rmsUserInfo, "mobile", "")],
                    ["name" => '提交时间', "value" => Carbon::now()->toDateTimeString()],
                )
                ->msgSend(["path" => "pages/self-contained/index?id={$intendedSiteSelectionId}&lat={$intendedSiteSelectionModel->latitude}&lng={$intendedSiteSelectionModel->longitude}&shopId=-1"]);
        }

        if (config('app.env') == 'prod') {
            // 生产环境四驱群的推送
            $areaRobotJson = ConfigModel::query()
                ->where('module', 'wanggui')
                ->where('name', 'areaRobots')
                ->value('value');
            $areaRobotArr  = json_decode($areaRobotJson, true);
            foreach ($areaRobotArr as $area => $robot) {
                $provinceLen = mb_strlen($area);
                if (mb_substr($intendedSiteSelectionModel->addressPrefix, 0, $provinceLen) == $area) {
                    $robotConfig['token']  = substr($robot['webhook'], (strripos($robot['webhook'], '/') + 1));
                    $robotConfig['secret'] = $robot['sign'];
                }
            }

            if (isset($robotConfig)) {
                Factory::feiShu()
                    ->setToken($robotConfig['token'])
                    ->setSecret($robotConfig['secret'])
                    ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($cardContent))
                    ->send();
            }
        }

    }
}
